import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
  message
} from 'antd'
import styles from './index.module.scss'
import { Link, useHistory } from 'react-router-dom'
import { ArticleStatus } from '@/api/constants'
import errImg from '@/assets/error.png'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { useState, useEffect } from 'react'
import { getArticles, delArticle } from '@/api'
import Channels from '@/components/Channels'

const { RangePicker } = DatePicker
const { confirm } = Modal

function Article () {
  const history = useHistory()
  const [articles, setArticles] = useState([])
  const [total, setTotal] = useState(0)
  const [form] = Form.useForm()
  // 获取文章列表
  async function getData (params) {
    const res = await getArticles(params)
    setArticles(res.data.results)
    setTotal(res.data.total_count)
  }
  // 参数格式化
  const formatParams = values => {
    const params = {}
    if (values.status !== -1) {
      params.status = values.status
    }
    if (values.channel_id) {
      params.channel_id = values.channel_id
    }
    if (values.date) {
      params.begin_pubdate = values.date[0].format('YYYY-MM-DD hh:mm:ss')
      params.end_pubdate = values.date[1].format('YYYY-MM-DD hh:mm:ss')
    }
    return params
  }
  useEffect(() => {
    getData()
  }, [])
  // 筛选
  const onFinish = values => {
    getData(formatParams(values))
  }
  // 分页组件修改
  const onChange = (page, pageSize) => {
    const params = formatParams(form.getFieldsValue())
    params.page = page
    params.per_page = pageSize
    getData(params)
  }
  // 删除弹框
  const showConfirm = id => {
    confirm({
      title: '提示',
      icon: <DeleteOutlined />,
      content: '你确定要删除吗？',
      async onOk () {
        await delArticle(id)
        message.success('删除成功')
        getData()
      }
    })
  }
  // 表格列配置
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'cover',
      render (cover) {
        if (cover.type === 0) {
          return <img src={errImg} className='cover' alt='' />
        } else {
          return <img src={cover.images[0]} className='cover' alt='' />
        }
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render (status) {
        const res = ArticleStatus.find(i => i.id === status)
        return <Tag color={res.color}>{res.name}</Tag>
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count'
    },
    {
      title: '操作',
      key: 'action',
      render (action) {
        return (
          <Space>
            <Button
              type='primary'
              shape='circle'
              icon={<EditOutlined />}
              onClick={() => {
                history.push('/home/publish/' + action.id)
              }}
            />
            <Button
              type='primary'
              shape='circle'
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                showConfirm(action.id)
              }}
            />
          </Space>
        )
      }
    }
  ]

  return (
    <div className={styles.article}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          form={form}
          initialValues={{ status: -1 }}
          onFinish={onFinish}
          autoComplete='off'
        >
          <Form.Item label='状态' name='status'>
            <Radio.Group>
              {ArticleStatus.map(i => {
                return (
                  <Radio value={i.id} key={i.id}>
                    {i.name}
                  </Radio>
                )
              })}
            </Radio.Group>
          </Form.Item>
          <Form.Item label='频道' name='channel_id'>
            <Channels />
          </Form.Item>
          <Form.Item label='日期' name='date'>
            <RangePicker />
          </Form.Item>
          <Form.Item wrapperCol={{ span: 8 }}>
            <Button type='primary' htmlType='submit'>
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title={`根据筛选条件共查询到 ${total} 条结果：`}>
        <Table
          columns={columns}
          dataSource={articles}
          rowKey='id'
          pagination={{ position: ['bottomCenter'], total, onChange }}
        />
      </Card>
    </div>
  )
}

export default Article
